﻿using System;
using System.Messaging;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.MsmqIntegration;
using Aluetjen.EMailService.Contract;

namespace Aluetjen.EmailService.Client
{
    public class EmailClient : IEmailClient
    {
        private readonly IServiceClientFactory<IEmailService> _clientFactory;

        public ClientCredentials ClientCredentials
        {
            get { return _clientFactory.ClientCredentials; }
        }

        /// <summary>
        /// Creates an email client to send messages to a local MSMQ called 'Mail'.
        /// </summary>
        public EmailClient()
            : this("net.msmq://./private/Mail")
        {
        }

        /// <summary>
        /// Creates an email client to sends messages to a MSMQ.
        /// </summary>
        /// <param name="queue">Name of the queue in the format 'net.msmq://localhost/private/Mail'"</param>
        public EmailClient(string queue)
        {
            _clientFactory = new ServiceClientFactory<IEmailService>(new NetMsmqBinding(NetMsmqSecurityMode.None), new EndpointAddress(queue));
        }

        public EmailClient(string address, Binding binding)
        {
            _clientFactory = new ServiceClientFactory<IEmailService>(binding, new EndpointAddress(address));
        }

        public EmailClient(string address, string bindingConfiguration)
        {
            _clientFactory = new ServiceClientFactory<IEmailService>(bindingConfiguration, address);
        }

        public void Send(MailMessage message)
        {
            var client = _clientFactory.CreateClient();

            try
            {
                client.Send(message);
            }
            finally
            {
                _clientFactory.DisposeClient(client);
            }
        }

        public void Send(string from, string recipients, string subject, string body, bool isBodyHtml = false)
        {
            var message = new MailMessage(from, recipients, subject, body, isBodyHtml);

            Send(message);
        }

        public void Dispose()
        {
            var clientFactory = _clientFactory as IDisposable;

            if(clientFactory != null) clientFactory.Dispose();
        }
    }
}
